<template>
  <div id='inform'>
    <el-dialog :title="'通知内容设置'" :destroy-on-close="true" :before-close="close"
      :close-on-click-modal="false" :visible.sync="informOpen" width="800px" append-to-body>
      <div class="body">
        <el-form ref="form" :model="informForm" label-position="right" :rules="rules"
          label-width="120px">
          <el-form-item label="通知名称:" prop="name">
            <el-input v-model="informForm.name" maxlength="12" :show-word-limit="true"
              placeholder="请输入通知名称" />
          </el-form-item>
          <el-form-item label="通知正文:" prop="content">
            <el-input v-model="informForm.content" type="textarea" :rows="5" :show-word-limit="true"
              maxlength="180" placeholder="请输入通知正文" />
          </el-form-item>
          <el-form-item label="通知部门:" prop="dept">
            <el-input v-model="informForm.dept" maxlength="12" :show-word-limit="true"
              placeholder="请输入通知部门" />
          </el-form-item>
          <el-form-item label="通知时间:" prop="date">
            <el-date-picker v-model="informForm.date" style="width:100%;" type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择通知时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="通知图片背图:" prop="image">
            <!-- <el-input v-model="informForm.date" maxlength="30" placeholder="请输入通知部门" /> -->
            <el-image v-for="(item) in url" @click="imageFun(item)"
              :class="{imgClass: image == item.name }"
              style="width: 108px; height: 80px;margin: 0 10px;cursor: pointer;" :src="item.url"
              :key="item.name" :fit="'fill'"></el-image>
          </el-form-item>
          <el-form-item label="" prop="">
            <el-image v-show="preview"
              :style="`width: ${108*5.5}px; height: ${80*5.5}px;margin: 0 10px;`"
              :src="preview" :fit="'fill'"></el-image>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button   @click="submit('预览')">预 览</el-button>
        <el-button  @click="submit('提交')">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import informBg1 from '@/assets/images/informBg1.jpg';
import informBg2 from '@/assets/images/informBg2.jpg';
import informBg3 from '@/assets/images/informBg3.jpg';
export default {
  name: 'inform',
  components: {},
  props: {
    informOpen: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 通知设置
      informForm: {
        name: null,
        content: null,
        dept: null,
        date: null,
        image: null,
      },
      url: [
        {
          name: 'bg1',
          url: informBg1,
        },
        {
          name: 'bg2',
          url: informBg2,
        },
        {
          name: 'bg3',
          url: informBg3,
        },
      ],
      preview: '',
      image: 'bg1',
      imageUrl: informBg1,
      rules: {
        name: [
          { required: true, message: '通知名称不能为空', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '通知正文不能为空', trigger: 'blur' },
        ],
        dept: [
          { required: true, message: '通知部门不能为空', trigger: 'blur' },
        ],
        date: [
          { required: true, message: '通知时间不能为空', trigger: 'blur' },
        ],
      },
    };
  },
  computed: {},
  created() {
    // if (process.client){}
  },
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  methods: {
    imageFun(item) {
      this.image = item.name;
      this.imageUrl = item.url;
    },
    close() {
      this.resetForm('form');
      this.preview = null
      this.$emit('informClose');
    },
    submit(val) {
      const _this = this;
      this.$refs.form.validate((valid) => {
        if (valid) {
          let img = new Image();
          img.crossOrigin = '';
          img.src = _this.imageUrl;
          img.width = 1080;
          img.height = 800;
          img.onload = function () {
            let canvas = document.createElement('canvas');
            let w = (canvas.width = img.width);
            let h = (canvas.height = img.height);
            let ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, w, h);
            _this.textEllipsis(ctx, _this.informForm.content, 42, 168);
            ctx.font = 'bold 48px serif';
            ctx.textAlign = 'center';
            ctx.fillText(_this.informForm.name, w / 2, 80);
            ctx.font = 'bold 48px serif';
            ctx.textAlign = 'left';
            ctx.fillText(
              _this.informForm.dept,
              w - ctx.measureText(_this.informForm.dept).width - 42,
              700
            );
            ctx.font = '42px serif';
            ctx.fillText(
              _this.informForm.date,
              w - ctx.measureText(_this.informForm.date).width - 42,
              750
            );
            // console.log(canvas.toDataURL('image/jpeg'));
            if (val == '预览') {
              _this.preview = canvas.toDataURL('image/jpeg');
            } else if (val == '提交') {
              _this.$emit(
                'submit',
                canvas.toDataURL('image/jpeg'),
                _this.informForm.name
              );
            }
          };
        }
      });
    },
    // 绘制N行文字，第二行开始填满canvas宽度，可设置左右padding，第一行可设置起点坐标。第二行溢出部分以省略号结尾。
    /**
     *
     * @param ctx 2d上下文对象
     * @param text 绘制文本
     * @param x 坐标轴x位置
     * @param y 坐标轴y位置
     * @param options 包含 maxWidth 最大宽度，lineHeight 文字行高，row 限制行数，textIndent 首行缩进，fontSize 文字大小
     */
    textEllipsis(ctx, text, x, y, options) {
      ctx.save();
      if (
        typeof text !== 'string' ||
        typeof x !== 'number' ||
        typeof y !== 'number'
      ) {
        return;
      }
      let defaultOpt = {
        maxWidth: 1040, // 输出多行文字最大宽度
        lineHeight: 72, // 行高
        row: 1000, // 最多行数
        textIndent: 72, // 首行缩进
        fontSize: 36, // 字体大小
      };
      let params = Object.assign({}, defaultOpt, options);
      // 分割文本
      let textArr = text.split('');
      // 文本最终占据高度
      let textHeight = 0;
      // 每行显示的文字
      let textOfLine = '';
      // 控制行数
      let limitRow = params.row;
      let rowCount = 0;
      // 循环分割的文字数组
      for (let i = 0; i < textArr.length; i++) {
        // 获取单个文字或字符
        let singleWord = textArr[i];
        // 连接文字
        let connectText = textOfLine + singleWord;
        // 计算接下来要写的是否是最后一行
        let isLimitRow = limitRow ? rowCount === limitRow - 1 : false;
        // 最后一行则显示省略符,否则显示连接文字
        let measureText = isLimitRow ? connectText + '...' : connectText;
        // console.log(measureText);
        // 设置字体并计算宽度,判断是否存在首行缩进
        ctx.font = `normal 500 ${params.fontSize}px "sans-serif"`;
        let width = ctx.measureText(measureText).width; // 文字宽度
        // 首行需要缩进满足条件
        let conditionIndent = params.textIndent && rowCount === 0; // 判断是否需要缩进
        let measureWidth = conditionIndent ? width + params.textIndent : width; // 根据缩进情况设置行数
        // 大于限制宽度且已绘行数不是最后一行，则写文字
        // 大于宽度限制表示可以绘制
        if (measureWidth > params.maxWidth && i > 0 && rowCount !== limitRow) {
          // 如果是最后一行，显示计算文本
          measureText = measureText.slice(0, -4) + '...'; // 删除最后一个字符
          let canvasText = isLimitRow ? measureText : textOfLine;
          let xPos = conditionIndent ? x + params.textIndent : x; // 行首X轴坐标
          // 写文字
          ctx.fillStyle = '#000';
          // console.log(666666666666);
          ctx.fillText(canvasText, xPos, y);
          // 下一行文字
          textOfLine = singleWord;
          // 记录下一行位置
          y += params.lineHeight;
          // 计算文本高度
          textHeight += params.lineHeight;
          rowCount++; // 绘制文字后行数加1

          if (isLimitRow) {
            // 行数到达限制
            break;
          }
        } else {
          // 不大于最大宽度，继续拼接
          textOfLine = connectText;
        }
      }
      if (rowCount !== limitRow) {
        // 单行文字走这边
        let xPos =
          params.textIndent && rowCount === 0 ? x + params.textIndent : x;
        ctx.fillStyle = '#000';
        // console.log('989898989898');
        ctx.fillText(textOfLine, xPos, y);
      }
      // 计算文字总高度
      let textHeightVal = rowCount < limitRow ? params.lineHeight : textHeight;
      ctx.restore();
      return textHeightVal;
    },
  },
};
</script>
<style lang='scss' scoped>
#inform {
  width: 100%;
  height: 100%;
}
.body {
  width: 100%;
  height: 600px;
  overflow: hidden;
  overflow-y: auto;
  padding: 0 10px;
}
.imgClass {
  border: 1px solid #67c23a;
  padding: 5px;
}
</style>